import { debounceGol, getJsRandom } from '@/system/utils/commonUtils';
import _ from 'lodash';

let globalCommonFun = {};
function globalResize() {
    window.addEventListener(
        'resize',
        // _.throttle(() => , 400),
        () => {
            let wh = window.innerHeight || (document.documentElement && document.documentElement.clientHeight) || document.body.clientHeight;
            for (const globalCommonFunKey in globalCommonFun) {
                if (globalCommonFun[globalCommonFunKey] && typeof globalCommonFun[globalCommonFunKey] === 'function') {
                    globalCommonFun[globalCommonFunKey](wh);
                }
            }
        },
    );
}
globalResize();

/**
 * v-resize 监听窗口变化
 */
export function resizeDirective(app) {
    app.directive('resize', {
        mounted(el, binding) {
            let { value } = binding;
            if (!value) {
                value = 0;
            }
            value = +value;
            let whTmp = window.innerHeight || (document.documentElement && document.documentElement.clientHeight) || document.body.clientHeight;

            el._resizeId = 'resize_' + getJsRandom(100, 999);
            globalCommonFun[el._resizeId] = _.debounce((wh) => {
                let htmlH = +wh - +value - 0 + 'px';
                el.style.height = htmlH;
            }, 400);
            globalCommonFun[el._resizeId](whTmp);
        },
        unmounted(el, binding) {
            el._resizeId && delete globalCommonFun[el._resizeId];
        },
    });
}

export function fresizeDirective(app) {
    app.directive('fresize', {
        mounted(el, binding) {
            let { value } = binding;
            if (!value) {
                value = 0;
            }
            value = +value;
            let whTmp = window.innerHeight || (document.documentElement && document.documentElement.clientHeight) || document.body.clientHeight;

            el._resizeId = 'resize_' + getJsRandom(100, 999);
            globalCommonFun[el._resizeId] = (wh) => {
                let htmlH = +wh - +value - 0 + 'px';
                el.style.height = htmlH;
            };
            globalCommonFun[el._resizeId](whTmp);
        },
        unmounted(el, binding) {
            el._resizeId && delete globalCommonFun[el._resizeId];
        },
    });
}
